package org.zlex.chapter03;

import util.SkyLogger;

import java.security.*;

/**
 * @author : wushikai
 * <p>
 * date : 2021-04-22
 *
 * 3 -11
 */
public class SignatureDemo {

    static SkyLogger log = new SkyLogger();



    /**
     * 非对称加密进行签名;
     * */
    public  static void signTest( ) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {

        byte[] data = "下单信息".getBytes();


        KeyPairGenerator  gen = KeyPairGenerator.getInstance("DSA");  //RSA 不行吗?

        gen.initialize(1024);


        KeyPair keyPair = gen.generateKeyPair();

        String algorithm = gen.getAlgorithm();

        // 实例化 签名对象
        Signature signature = Signature.getInstance(algorithm);
        // 初始化用于签名操作
        signature.initSign(  keyPair.getPrivate());
        //更新
        signature.update(data);

        //获得签名
        byte[] sign = signature.sign();

        //使用公钥验证签名
        signature.initVerify( keyPair.getPublic());

        //   更新签名对象
        signature.update(data);

        //获得验证结果;
        boolean verify = signature.verify(sign);


        log.info("verify => " + verify);
    }







    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {

        signTest();


    }





}
